<?php

namespace app\common\model\shop;

use app\admin\model\shop\SkuGoods;
use think\Model;

/**
 * sku商品插件
 */
class SkuProduct extends Model
{
    // 表名
    protected $name = 'jeek_shop_sku_product';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 追加属性
    protected $append = [
        'discount_price',
        'item_name',
        'image_str',
    ];
    public function getImageStrAttr($value, $data)
    {
        return $data['image'] ? cdnurl($data['image'], true) : $data['image'];
    }

    // 获取商品一折价格区间
    public function getDiscountPriceAttr($v, $d)
    {
        return $d['price'] > 0 ? bcmul($d['price'], 0.1, 2) : 0;
    }

    public function goods()
    {
        return $this->belongsTo(SkuGoods::class, 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function getItemNameAttr($v, $d)
    {
        $keys = explode('_', $d['key']);
        $data =  SkuItem::whereIn('id', $keys)->field('spec_id,name')->select();
        foreach ($data as &$v) {
            $v->spec_name = SkuSpec::where('id', $v['spec_id'])->value('name');
        }
        return $data;
    }

    /**
     * 判断商品是否能下单
     * @param int $product_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function checkGoods($data)
    {
        $goods = $data['goods'];
        $product = $data['product'];
        if (!isset($goods) || !$goods) {
            exception('商品【' . $goods['name'] . '】不存在');
        }
        if (!isset($product) || !$product) {
            exception('商品【' . $goods['name'] . '】规格不存在');
        }
        if ($product['stock'] < $data['num']) {
            exception('商品【' . $goods['name'] . '】库存不足，不能下单');
        }
        if ($goods['status'] == '0' || $product['status'] == '0') {
            exception('商品【' . $goods['name'] . '】已下架，不能下单');
        }
        if ($goods['deletetime'] != null) {
            exception('商品【' . $goods['name'] . '】已删除，不能下单');
        }
        if ($goods['type'] == 4) {
            $time = time();
            $friday = strtotime(date('Y-m-d 20:00:00', strtotime("Friday"))); //本周五开始时间
            $sunday = strtotime(date('Y-m-d 20:00:00', strtotime("Sunday"))); //本周日开始时间
            if ($time < $friday && $time > $sunday) {
                exception('请于每周五晚8点到每周日晚8点购买：会员福利商品【' . $goods['name'] . '】');
            }
        }
     
    }


    /**
     * 增销减库
     * @param int $product_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function reduceInventory($goods_id, $product_id, $num)
    {

        try {
            $product = self::get($product_id);
            $goods = SkuGoods::get($goods_id);
            if ($product->stock < $num) {
                exception('库存不足');
            }
            $goods->setInc('sales', $num);
            $product->setDec('stock', $num);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
    /**
     * 减销增库
     * @param int $goods_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function stockUp($goods_id, $product_id, $num)
    {
        try {
            $product = self::get($product_id);
            $goods = SkuGoods::get($goods_id);
            if ($product->stock < $num) {
                exception('库存不足');
            }
            $goods->setDec('sales', $num);
            $product->setInc('stock', $num);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
}
